import Bb from 'backbone';
import Mn from 'backbone.marionette';
import Radio from 'backbone.radio';
import Router from './components/Router.js';
import RootComponent from './views/RootComponent.js';
import Controller from './components/Controller.js';


const AppClass = Mn.Application.extend({
    channelName: 'progressInvoicingApp',
    radioEvents: {
        "navigate": 'onNavigate',
        "show:modal": "onShowModal",
        "workitem:edit": "onWorkItemEdit",
        // product changed
        "product:changed": "onProductChanged",
    },
    onBeforeStart(app, options) {
        this.config = Radio.channel('config');
        this.facade = Radio.channel('facade');
        this.chapters = this.facade.request('get:collection', 'progress_invoicing_chapters');
        const model = this.facade.request('get:model', 'display_options');

        this.rootView = new RootComponent({
            collection: this.chapters,
            section: options['section']
        });
        this.controller = new Controller({
            rootView: this.rootView,
            chapters: this.chapters,
            section: options['section']
        })
        this.listenTo(model, 'saved:display_units', () => this.onNavigate('index'));
        new Router({
            controller: this.controller
        });
    },
    onStart(app, options) {
        this.showView(this.rootView);
    },
    onNavigate(route_name, parameters) {
        let dest_route = route_name;
        if (!_.isUndefined(parameters)) {
            dest_route += "/" + parameters;
        }
        window.location.hash = dest_route;
        Bb.history.loadUrl(dest_route);
    },
    onWorkItemEdit(model) {
        this.controller.editWorkItem(model);
    },
    onProductChanged(model) {
        // Cas 1 Product: rien à faire
        const requests = []

        if (!model.has("type_")) {
            // WorkItem : on recharge la collection et le work associé
            requests.push(
                model.collection.fetch()
            );
            requests.push(model.collection._parent.fetch());

        } else if (model.get('type_') == 'progress_invoicing_work') {
            requests.push(model.items.fetch());
        }
        $.when(requests).then(
            () => {
                window.location.hash = "#index";
                this.controller.index();
                this.facade.trigger('changed:task');
            }
        );
    },
});

export default AppClass;